﻿using LpbPrj.Client.Event;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Windows;

namespace LpbPrj.Client.ViewModels
{
    public class WaitingViewModel : BindableBase
    {
        /// <summary>
        /// 窗口释放
        /// </summary>
        public DelegateCommand<RoutedEventArgs> MainUnloadedCommand =>
            new Lazy<DelegateCommand<RoutedEventArgs>>(() => new DelegateCommand<RoutedEventArgs>(p =>
            {
                System.Diagnostics.Debug.WriteLine("WaitingViewModel---UnloadedCommand");

                //释放所有事件，验证
                for (int i = 0; i < SubscriptionTokenList.Count; i++)
                {
                    _eventAggregator.GetEvent<MessageSentEvent>().Unsubscribe(SubscriptionTokenList[i]);
                }
                System.Diagnostics.Debug.WriteLine("WaitingViewModel---EventUnsubscribe");

            })).Value;



        protected readonly IEventAggregator _eventAggregator;
        public WaitingViewModel(IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;

            //等待窗口
            var loadingControlVisible = _eventAggregator.GetEvent<MessageSentEvent>()
                .Subscribe(obj =>
                {
                    if (obj.MsgParam != null)
                    {
                        string title = obj.MsgParam.GetValue<string>("LoadingTip");
                        if (!string.IsNullOrEmpty(title)) LoadingTip = title;

                        LoadingVisibility = obj.MsgParam.GetValue<bool>("Visible") ? Visibility.Visible : Visibility.Collapsed;
                    }
                }, ThreadOption.UIThread, false, (filter) => filter.MsgKey.Equals(EventKey.LoadingControlVisible));
            SubscriptionTokenList.Add(loadingControlVisible);
        }

        /// <summary>
        /// 所有事件
        /// </summary>
        protected List<SubscriptionToken> SubscriptionTokenList = new List<SubscriptionToken>();

        /// <summary>
        /// 等待窗口提示语
        /// </summary>
        protected string _loadingTip = "Waiting";
        public string LoadingTip { get => _loadingTip; set => SetProperty(ref _loadingTip, value); }

        /// <summary>
        /// 等待窗口是否显示
        /// </summary>
        protected Visibility _loadingVisibility = Visibility.Collapsed;
        public Visibility LoadingVisibility { get => _loadingVisibility; set => SetProperty(ref _loadingVisibility, value); }

    }
}
